<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
  <meta name="generator" content=
  "HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org">

  <title>template</title>
  <link href="../cppreference.css" rel="stylesheet" type="text/css">
</head>

<body>
<table>
  <tr>
  <td>
  <div class="body-content">

  <div class="header-box">
    <a href="../index.html">cppreference.com</a> &gt; <a href=
    "index.html">C/C++ Keywords</a> &gt; <a href=
    "template.html">template</a>
  </div>

  <div class="name-format">
    template
  </div>

  <div class="syntax-name-format">
    Syntax:
  </div>
  <pre class="syntax-box">
  template &lt;class data-type&gt; return-type name( parameter-list ) {
  statement-list;
  }
</pre>

  <p>Templates are used to create generic functions and can operate on
  data without knowing the nature of that data. They accomplish this by
  using a placeholder data-type for which many other <a href=
  "../data_types.html">data types</a> can be substituted.</p>

  <div class="related-examples-format">
    Example code:
  </div>

  <div class="related-examples">
    <p>For example, the following code uses a template to define a
    generic swap function that can swap two variables of any type:</p>
    <pre class="example-code">
   template&lt;class X&gt; void genericSwap( X &amp;a, X &amp;b ) {
     X tmp;             

     tmp = a;
     a = b;
     b = tmp;
   }
   int main(void) {
     ...
     int num1 = 5;
     int num2 = 21;
     cout &lt;&lt; &quot;Before, num1 is &quot; &lt;&lt; num1 &lt;&lt; &quot; and num2 is &quot; &lt;&lt; num2 &lt;&lt; endl;
     genericSwap( num1, num2 );
     cout &lt;&lt; &quot;After, num1 is &quot; &lt;&lt; num1 &lt;&lt; &quot; and num2 is &quot; &lt;&lt; num2 &lt;&lt; endl;
     char c1 = &#39;a&#39;;
     char c2 = &#39;z&#39;;
     cout &lt;&lt; &quot;Before, c1 is &quot; &lt;&lt; c1 &lt;&lt; &quot; and c2 is &quot; &lt;&lt; c2 &lt;&lt; endl;
     genericSwap( c1, c2 );
     cout &lt;&lt; &quot;After, c1 is &quot; &lt;&lt; c1 &lt;&lt; &quot; and c2 is &quot; &lt;&lt; c2 &lt;&lt; endl;
     ...
     return( 0 );
   }            
</pre>
  </div>

  <div class="related-name-format">
    Related topics:
  </div>

  <div class="related-content">
    <a href="typename.html">typename</a>
  </div>
  </div>
  </td>
  


  </tr>
  </table>
</body></html>
